const fs = require('fs')
const path = require('path')
let filesList = []
let jsFilesList = []
function readFileList(dir, filesList = []) {
  const files = fs.readFileSync(dir)
  files.forEach(item => {
    let fullPath = path.join(dir, item)
    const stat = fs.statSync(fullPath)
    if(stat.isDirectory()) {
      readFileList(path.join(dir, item), filesList)
    } else if(fullPath.endsWith('.vue')) {
      filesList.push(fullPath)
    } else if(/(.ts|.js)$/g.test(fullPath)) {
      jsFilesList.push(fullPath)
    }
  })
}
readFileList(path.resolve(__dirname, '../src/'), filesList)
fs.stat(path.resolve(__dirname, '../src/local'), function(err, statObj) {
  if(!statObj) {
    fs.mkdir(path.resolve(__dirname, '../src/local'), function(err) {
      let arr = [...filesList, ...jsFilesList]
      writeFile(arr, 'index')
    })
  }
})
function writeFile(fileArr, fileName) {
  const reg1 = /\$tb?/
  const reg2 = /\$tb?/
  const obj = fileArr.reduce((pre, cur) => {
    let fileSuffix = cur.match(/(.ts|.js|.vue)$/g)[0]
    let pathName = path.basename(cur, fileSuffix)
    if(pathName === 'index') {
      const pathArr = cur.split(path.sep)
      pathName = pathArr[pathArr.length - 2]
    }
    let pkg = fs.readFileSync(cur, 'utf-8')
    let strArr1 = pkg.matchAll(reg1)
    let strArr2 = pkg.matchAll(reg2)
    for(const matchx of strArr1) {
      pre[matchx[2]] = matchx[4]
    }
    for(const matchy of strArr2) {
      let regText = /text\s*\n*:\s*\n*(['"])(.*?)\1/
      if(regText.test(matchy[3])) {
        let strArrText =  matchy[3].match(regText)
        pre[matchy[2]] = strArrText[2]
      }
    }
    return pre
  }, {})
  fs.writeFile(path.resolve(__dirname, `../src/local/${fileName}.json`),JSON.stringify(obj), 'utf-8', err => {
    
  })
}